package org.sgroup.imenu.util;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.sgroup.imenu.R;
import org.sgroup.imenu.bo.CatItem;
import org.sgroup.imenu.bo.Category;
import org.sgroup.imenu.bo.Item;
import org.sgroup.imenu.service.IMenuService;
import org.sgroup.imenu.service.ObjectMapper;
import org.sgroup.imenu.service.XmlDocument;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;

public class SyncIData {
	String input = "<input user=\"lbnam\" pass=\"123456\"/>";
	String _res;
	List<Category> cats = null;
	List<Item> items = null;
	List<CatItem> cItems = null;
	public List<String> urlmig = new ArrayList<String>();
	IMenuService iService = new IMenuService();
	Context context;
	ProgressDialog prog;

	public SyncIData(Context _context, ProgressDialog _prog) {
		this.context = _context;
		this.prog = _prog;
	}

	public Boolean SynAllData() {
		// Bimap bm= LoadBitmap.GetBitmap(this.context,path);
		CData cDa = new CData(this.context);
		if (!cDa.CheckConnection()) {
			return false;
		}
		if (cDa.CheckVersionData("Data.xml", "1.1")){
			this.prog.dismiss();
			return true;}
		else {
			GetData();
			GetImg();
		}
		return true;
	}

	public void GetImg() {
		int size = items.size();
		for (int c = 0; c < size; c++) {
			String imgItem = items.get(c).ImageFile;
			if (imgItem != null)
				urlmig.add(imgItem);
		}
		new DownloadMultiTask(this.context, this.prog).execute(urlmig);

	}
	public void GetData() {
		_res = iService.getAll(input);
		cats = ObjectMapper.CSVToObject(_res, Category.class);
		items = ObjectMapper.CSVToObject(_res, Item.class, 1);
		cItems = ObjectMapper.CSVToObject(_res, CatItem.class, 2);
		try{
		int size = cats.size();
		for (int c = 0; c < size; c++) {
			int _idParent = cats.get(c).ParentID;
			String imgCat = cats.get(c).ImageFile;
			if (imgCat != null)
				urlmig.add(imgCat);
			if (_idParent != 0) {
				ArrayList<Integer> idItems = cats.get(c).GetItems(cItems);
				for (int idi : idItems) {
					int itemPos = FindPosItem(idi, items);
					cats.get(c).AddItem(items.get(itemPos));
				}
				int pos = FindPos(cats.get(c).ParentID, cats);
				if (pos > 0) {
					cats.get(pos).AddChild(cats.remove(c));
					c--;
					size--;
				}
			}
		}
		CData cData = new CData(this.context);
		String strxml = IXmlMapper.MapToXML(Category.class, cats, true, "1.1");
		cData.SaveInnerStorage(strxml, "Data.xml");
		}
		catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}

	public int FindPos(int id, List<Category> _cat) {
		for (int j = 0; j < _cat.size(); j++) {
			if (_cat.get(j).ID == id)
				return j;
		}
		return 0;
	}

	public int FindPosItem(int id, List<Item> _item) {
		for (int j = 0; j < _item.size(); j++) {
			if (_item.get(j).ID == id)
				return j;
		}
		return 0;
	}
	
}
